import { login, getInfo, getToken, setToken, removeToken } from '@/api/login'
import { setCurTenant } from '@/api/tenant'
import Cookies from 'js-cookie'
import { removeSlash } from '@/utils/removeIdSlash'
import { cloneDeep } from 'lodash'

const user = {
  namespaced: true,
  state: {
    user: '',
    status: '',
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    id: '',
    tenantId: '',
    sysTenantId: '',
    email: '',
    firstName: '',
    lastName: '',
    tenantList: [],
    scadaToken: Cookies.get('scadaToken') ? Cookies.get('scadaToken') : '',
    playedAlarmList: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      console.log('SET_ROLES', state.roles, roles)

      state.roles = roles
    },
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_EMAIL: (state, email) => {
      state.email = email
    },
    SET_FIRSTNAME: (state, firstName) => {
      state.firstName = firstName
    },
    SET_LASTNAME: (state, lastName) => {
      state.lastName = lastName
    },
    SET_TENANTID: (state, tenantId) => {
      state.tenantId = tenantId
    },
    SET_SYS_TENANTID: (state, tenantId) => {
      if (tenantId.sys) {
        state.sysTenantId = state.tenantId
        state.tenantId = tenantId.id
      } else {
        state.tenantId = tenantId.sysTenantId
        state.sysTenantId = ''
      }
    },
    SET_SCADA_TOKEN: (state, scadaToken) => {
      Cookies.set('scadaToken', scadaToken)
      state.scadaToken = scadaToken
    },
    SET_TENANT_LIST: (state, tenantList) => {
      state.tenantList = tenantList
      if (tenantList[0]) {
        setCurTenant(tenantList[0].id)
      }
    },
    ADD_PLAYED_ALARM: (state, id) => {
      state.playedAlarmList.push(id)
    }
  },

  actions: {
    // 登录
    Login({ dispatch, commit }, userInfo) {
      // const username = userInfo.username.trim()
      return new Promise<void>((resolve, reject) => {
        // const password = btoa(userInfo.password)
        // const pwds = password.split('').reverse()
        // const user = btoa(username)
        // .split('')
        // .reverse()
        const params = {
          username: userInfo.username,
          password: userInfo.password,
          verifyCode: userInfo.verifyCode,
          requestId: userInfo.requestId
          // username: username,
          // password: userInfo.password
        }
        login(params)
          .then(async response => {
            const data = response.data
            // if (data.scopes && data.scopes.length > 0) { // 验证返回的roles是否是一个非空数组
            //   commit('SET_ROLES', data.scopes)
            // } else {
            //   reject('getInfo: roles must be a non-null array !')
            // }
            setToken(data.token)
            commit('SET_TOKEN', data.token)
            // parse user id from token
            const tokenBody = JSON.parse(
              atob(
                data.token
                  .match(/\.(.*?)\./)[1]
                  .replace(/-/g, '+')
                  .replace(/_/g, '/')
              )
            )
            // FIXME: SET_ID is not working
            commit('SET_ID', tokenBody.userId)
            Cookies.set('userId', tokenBody.userId)
            dispatch('GetInfo').then(() => {
              resolve()
            })
          })
          .catch(error => {
            reject(error)
          })
      })
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise<any>((resolve, reject) => {
        getInfo(Cookies.get('userId'))
          .then(response => {
            const data = response.data
            const authority = [data.authority]
            if (authority && authority.length > 0) {
              // 验证返回的roles是否是一个非空数组
              // if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', authority)
            } else {
              reject('getInfo: roles must be a non-null array !')
            }
            commit('SET_NAME', data.name)
            commit('SET_AVATAR', data.avatar)
            commit('SET_TENANTID', data.tenantId.id)
            commit('SET_ID', data.id.id)
            commit('SET_EMAIL', data.email)
            commit('SET_FIRSTNAME', data.firstName)
            commit('SET_LASTNAME', data.lastName)
            Cookies.set('userId', data.id.id)
            const current_cookie = Cookies.get('Admin-Token')
            const changed = () => {
              location.href = '/home'
            }
            setInterval(() => {
              if (current_cookie !== Cookies.get('Admin-Token')) {
                changed()
              }
            }, 500)
            resolve(response)
          })
          .catch(error => {
            console.log(error, 'err login')
            reject(error)
          })
      })
    },

    // 跳转替换信息
    ToggleRoles: ({ commit }, role) => {
      commit('SET_ROLES', role)
    },
    ToggleTenantId: ({ commit }, tenantId) => {
      commit('SET_SYS_TENANTID', tenantId)
    },
    ToggleToken: ({ commit }, token) => {
      commit('SET_TOKEN', token)
    },
    ToggleScadaToken: ({ commit }, token) => {
      commit('SET_SCADA_TOKEN', token)
    },

    // 登出
    LogOut({ commit }) {
      return new Promise<void>(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resolve()
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise<void>(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 动态修改权限
    ChangeRoles({ commit }, role) {
      return new Promise<void>(resolve => {
        commit('SET_TOKEN', role)
        setToken(role)
        getInfo(role).then(response => {
          const data = response.data
          commit('SET_ROLES', data.roles)
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          resolve()
        })
      })
    },

    // 设置企业列表
    getTenantList({ commit }, tenantList) {
      const dataList = cloneDeep(tenantList)
      console.log(dataList)
      if (tenantList && tenantList.length) {
        dataList.forEach(tenant => (tenant.id = removeSlash(tenant.id.id)))
      }
      commit('SET_TENANT_LIST', dataList)
    },

    addPlayedAlarm({ commit }, id) {
      commit('ADD_PLAYED_ALARM', id)
    }
  }
}

export default user
